package com.ciwong.epaper.modules.me.ui;

import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;

import com.ciwong.epaper.R;
import com.ciwong.epaper.bean.RfTokenInfo;
import com.ciwong.epaper.modules.cordva.BaseHtmlActicity;
import com.ciwong.epaper.modules.me.dao.MeDao;
import com.ciwong.epaper.util.EJumpManager;
import com.ciwong.epaper.util.FeedbackUtil;
import com.ciwong.epaper.util.HttpRequest;
import com.ciwong.epaper.util.IntentFlag;
import com.ciwong.libs.utils.CWLog;
import com.ciwong.libs.utils.CWSys;
import com.ciwong.libs.utils.volley.BaseRequest;
import com.ciwong.mobilelib.i.BaseCallBack;
import com.ciwong.mobilelib.utils.BaseConstants;

import org.apache.cordova.engine.SystemWebView;

import java.io.IOException;

/**
 * 习网隐私协议
 * Created by paull on 2017/10/11.
 */

public class AgreementActivity extends BaseHtmlActicity {
    /**
     * 登陆页面经来
     */
    public static final String LOGIN_ACTION = "LOGIN_ACTION";
    /**
     * 欢迎页面进来
     */
    public static final String WECOME_ACTION = "WECOME_ACTION";
    private LinearLayout agreement_llayout;
    private Button btn_go_black, btn_go_main;
    private String action, url;
    private String packageName = "";

    @Override
    protected void findViews() {
        super.findViews();
        agreement_llayout = findViewById(R.id.agreement_llayout);
        btn_go_black = findViewById(R.id.btn_go_black);
        btn_go_main = findViewById(R.id.btn_go_main);
    }

    @Override
    protected void initEvent() {
        super.initEvent();
        btn_go_black.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        btn_go_main.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (WECOME_ACTION.equals(action)) {
                    try {
                        CWSys.setSharedBoolean("isFirstUse" + packageName, false);//以后都不再是第一次使用
                        CWSys.setSharedBoolean("agreement" + packageName, true);//以后都不再显示同意按钮
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    //跳转新手引导
                    //EJumpManager.jumpToGuide(0, AgreementActivity.this);
                    //跳转到主界面
                    checkToken();
                } else {
                    finish();
                }
            }
        });
    }

    @Override
    protected void init() {
        super.init();
        registStatistics(false);
        packageName = getPackageName();
        String title = getIntent().getStringExtra(IntentFlag.INTENT_FLAG_TITLE);
        url = getIntent().getStringExtra(IntentFlag.INTENT_FLAG_URL);
        action = getIntent().getStringExtra(IntentFlag.INTENT_FLAG_ACTION);
        //是否显示同意、不同意按钮
        boolean isAgreement = false;
        //是否同意隐私协议打钩
        boolean privacyAgreement = false;
        try {
            isAgreement = CWSys.getSharedBoolean("agreement" + packageName, false);
            privacyAgreement = CWSys.getSharedBoolean("privacyAgreement" + packageName + getPackageManager()
                    .getPackageInfo(getPackageName(), 0).versionName, false);
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (isAgreement && privacyAgreement) {
            agreement_llayout.setVisibility(View.GONE);
            setTitleText(title);
        } else {
            agreement_llayout.setVisibility(View.VISIBLE);
            hideTitleBar();
        }
    }

    @Override
    public void loadData() {
        webView.setOnKeyBack(new SystemWebView.OnKeyBack() {
            @Override
            public boolean keyBack() {
                finish();
                return true;
            }
        });
        setStartURL(url);
        loadUrl(url);
    }

    private BaseRequest.VerifyInfo verifyInfo;

    private void checkToken() {
        try {
            verifyInfo = HttpRequest.getVerifyInfo();
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (null != verifyInfo) {
            String accessToken = verifyInfo.getAccessToken();
            String refreshToken = verifyInfo.getRefreshToken();
            if (!TextUtils.isEmpty(accessToken) && !TextUtils.isEmpty(refreshToken)) {
                updateUserToken(refreshToken);
            } else {
                goToMainActivity(false);
            }
        } else {
            goToMainActivity(false);
        }
    }

    private void goToMainActivity(boolean isLogin) {
        //是否同意隐私协议
        boolean privacyAgreement = false;
        try {
            privacyAgreement = CWSys.getSharedBoolean("privacyAgreement" + packageName + getPackageManager()
                    .getPackageInfo(getPackageName(), 0).versionName, false);
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (isLogin && privacyAgreement) {
            //用户已经登录
            EJumpManager.jumpToMain(0, this);
        } else {
            //用户未登录
            EJumpManager.jumpToLogin(0, this);
        }
        finish();
    }


    private void updateUserToken(String rfToken) {
        MeDao.getInstance().updateUserToken(rfToken, new BaseCallBack() {
            @Override
            public void success(Object data) {
                RfTokenInfo rfTokenInfo = (RfTokenInfo) data;
                String accessToken = rfTokenInfo.getAccessToken();
                String refreshToken = rfTokenInfo.getRefreshToken();
                String expires = rfTokenInfo.getRefreshToken();
                if (null != verifyInfo) {
                    verifyInfo.setAccessToken(accessToken);
                    verifyInfo.setRefreshToken(refreshToken);
                    verifyInfo.setExpiresIn(expires);
                    HttpRequest.setVerifyInfo(verifyInfo);
                    try {
                        CWSys.setSharedSerializable(BaseConstants.SHARE_KEY_VERITIFY_INFO,
                                verifyInfo);
                        //上报登录信息
                        FeedbackUtil.getInstance().asyncUploadUserLogin();
                        goToMainActivity(true);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                } else {
                    goToMainActivity(false);
                }
            }

            @Override
            public void failed(int errorCode, Object data) {
                goToMainActivity(false);
            }

            @Override
            public void failed(Object data) {
                goToMainActivity(true);
            }
        });
    }
}
